<?php
class Vnexpress_model extends CI_Model
{
    var $questions_collection = 'questions';
    var $answers_collection = 'answers';
    var $tags_collection = 'tags';
    var $url_question = 'http://demo.vnexpress.net/rss/microsoftfood?cate=1003137';
    var $url_answer = 'http://interactions.vnexpress.net/index/get?offset=0&limit=24&sort=like&objectid=[id]&objecttype=1&siteid=1000000';
    
	public function __construct()
	{
		parent::__construct();
        $this->load->library('cimongo/cimongo', '', 'mongo');
	}
    
    private function xml2array($url, $get_attributes = 1, $priority = 'tag')
    {
        $contents = "";
        if (!function_exists('xml_parser_create'))
        {
            return array ();
        }
        $parser = xml_parser_create('');
        if (!($fp = @ fopen($url, 'rb')))
        {
            return array ();
        }
        while (!feof($fp))
        {
            $contents .= fread($fp, 8192);
        }
        fclose($fp);
        xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parse_into_struct($parser, trim($contents), $xml_values);
        xml_parser_free($parser);
        if (!$xml_values)
            return; //Hmm...
        $xml_array = array ();
        $parents = array ();
        $opened_tags = array ();
        $arr = array ();
        $current = & $xml_array;
        $repeated_tag_index = array ();
        foreach ($xml_values as $data)
        {
            unset ($attributes, $value);
            extract($data);
            $result = array ();
            $attributes_data = array ();
            if (isset ($value))
            {
                if ($priority == 'tag')
                    $result = $value;
                else
                    $result['value'] = $value;
            }
            if (isset ($attributes) and $get_attributes)
            {
                foreach ($attributes as $attr => $val)
                {
                    if ($priority == 'tag')
                        $attributes_data[$attr] = $val;
                    else
                        $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
                }
            }
            if ($type == "open")
            {
                $parent[$level -1] = & $current;
                if (!is_array($current) or (!in_array($tag, array_keys($current))))
                {
                    $current[$tag] = $result;
                    if ($attributes_data)
                        $current[$tag . '_attr'] = $attributes_data;
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    $current = & $current[$tag];
                }
                else
                {
                    if (isset ($current[$tag][0]))
                    {
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                        $repeated_tag_index[$tag . '_' . $level]++;
                    }
                    else
                    {
                        $current[$tag] = array (
                            $current[$tag],
                            $result
                        );
                        $repeated_tag_index[$tag . '_' . $level] = 2;
                        if (isset ($current[$tag . '_attr']))
                        {
                            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                            unset ($current[$tag . '_attr']);
                        }
                    }
                    $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
                    $current = & $current[$tag][$last_item_index];
                }
            }
            elseif ($type == "complete")
            {
                if (!isset ($current[$tag]))
                {
                    $current[$tag] = $result;
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    if ($priority == 'tag' and $attributes_data)
                        $current[$tag . '_attr'] = $attributes_data;
                }
                else
                {
                    if (isset ($current[$tag][0]) and is_array($current[$tag]))
                    {
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                        if ($priority == 'tag' and $get_attributes and $attributes_data)
                        {
                            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                        }
                        $repeated_tag_index[$tag . '_' . $level]++;
                    }
                    else
                    {
                        $current[$tag] = array (
                            $current[$tag],
                            $result
                        );
                        $repeated_tag_index[$tag . '_' . $level] = 1;
                        if ($priority == 'tag' and $get_attributes)
                        {
                            if (isset ($current[$tag . '_attr']))
                            {
                                $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                                unset ($current[$tag . '_attr']);
                            }
                            if ($attributes_data)
                            {
                                $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                            }
                        }
                        $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
                    }
                }
            }
            elseif ($type == 'close')
            {
                $current = & $parent[$level -1];
            }
        }
        return ($xml_array);
    }
    
    public function crawlQuestions()
    {
        $data = $this->xml2array($this->url_question);
        $newsItems = $data['NewsML']['NewsItem'];

        $arrReturn = array();
        for ($i = 0, $n = count($newsItems); $i < $n; $i++) {
            $item = $newsItems[$i];
            $newsLines = $item['NewsLines'];
            $newsManagement = $item['NewsManagement'];
            $newsComponent = $item['NewsComponent']['NewsComponent'];
            
            $id = (int) $item['NewsComponent_attr']['Duid'];
            $title = $newsLines['HeadLine'];
            $description = $newsLines['Description'];
            $image = $newsComponent['ContentItem']['DataContent']['nitf']['body']['body.content']['media']['media-reference_attr']['source'];
            $tags = $newsComponent['item_keywords']['item_keyword'];
            $public_time = strtotime($newsManagement['ThisRevisionCreated']);
            
            $arrReturn[] = array(
                'vnexpress_id' => $id,
                'title' => $title,
                'description' => $description,
                'image' => $image,
                'tags' => $tags,
                'public_time' => $public_time,
                'create_time' => time()
            );
        }
        
        return $arrReturn;
    }
    
    public function insertQuestion($params)
    {
        $params['vnexpress_id'] = (int) $params['vnexpress_id'];
        // kiểm tra tồn tại câu hỏi
        $questionExist = $this->mongo->get_where($this->questions_collection, array('vnexpress_id' => $params['vnexpress_id']));
        if ($questionExist->result()) {
            return false;
        }
        // insert tags
        $tagsID = $this->insertTags($params['tags']);
        // update tag id vào params
        $params['tags'] = $tagsID;
        // upload image question
        $this->load->helper('upload');
        if ($params['image'] != '') {
            $titleSlug = strtolower(url_title(convert_accented_characters($params['title'])));
            $image = save_remote_file($params['image'], $titleSlug);
            $params['image'] = $image;
        }
        // insert question
        return $this->mongo->insert($this->questions_collection, $params);
    }
    
    public function insertTags($tags)
    {
        $tagsID = array();
        if (!is_array($tags)) {
            $tags = array($tags);
        }
        for ($i = 0, $n = count($tags); $i < $n; $i++) {
            $tag = $tags[$i];
            $tagSlug = strtolower(url_title(convert_accented_characters($tag)));
            // kiểm tra tồn tại tag
            $tagExist = $this->mongo->get_where($this->tags_collection, array('slug' => $tagSlug));
            if ($tagInfo = $tagExist->result()) {
                $tagsID[] = $tagInfo[0]->_id;
            } else {
                $tagParams = array(
                    'title' => $tag,
                    'slug' => $tagSlug,
                );
                $this->mongo->insert($this->tags_collection, $tagParams);
                $tagsID[] = $this->mongo->insert_id();
            }
        }
        return $tagsID;
    }
    
    public function crawlAnswers($id)
    {
        $id = (int) $id;
        $url = str_replace('[id]', $id, $this->url_answer);
        $data = file_get_contents($url);
        $json = str_replace('defaultCallback(', '', $data);
        $json = substr($json, 0, -2);
        $answers = json_decode($json);
        $answers = $answers->data->items;
        
        $arrReturn = array();
        for ($i = 0, $n = count($answers); $i < $n; $i++) {
            $answer = $answers[$i];
            $vnexpress_comment_id = (int) $answer->comment_id;
            $content = $answer->content;
            $full_name = $answer->full_name;
            $user_like = (int) $answer->userlike;
            $public_time = $answer->creation_time;
            
            $arrReturn[] = array(
                'vnexpress_question_id' => $id,
                'vnexpress_comment_id' => $vnexpress_comment_id,
                'content' => $content,
                'full_name' => $full_name,
                'public_time' => $public_time,
                'user_like' => $user_like,
                'create_time' => time()
            );
        }
        
        return $arrReturn;
    }
    
    public function insertAnswer($params)
    {
        // kiểm tra tồn tại câu trả lời
        $where = array('vnexpress_comment_id' => $params['vnexpress_comment_id']);
        $answerExist = $this->mongo->get_where($this->answers_collection, $where);
        if ($answer = $answerExist->result()) {
            $answer = $answer[0];
            // nếu thay đổi số like thì update
            if ($answer->user_like == $params['user_like']) {
                return false;
            } else {
                return $this->mongo
                    ->where($where)
                    ->update($this->answers_collection, $params);
            }
        }
        // insert answer
        return $this->mongo->insert($this->answers_collection, $params);
    }
}